﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;

namespace HYCableTrayConnection
{
	internal class HYTransitionConnection
	{
		public bool NewTransitionFitting(IList<CableTray> cableTrays)
		{
			bool result = false;
			if (cableTrays.Count < 2)
			{
				throw new System.ArgumentNullException("CableTray", "is null");
			}
			Document document = cableTrays[0].Document;
			if (!Common.IsSameCableTrayType(document, cableTrays))
			{
				throw new MyException("桥架的类型不一致");
			}
			HYCableTray<CableTray> hycableTray = new HYCableTray<CableTray>(cableTrays[0]);
			HYCableTray<CableTray> hycableTray2 = new HYCableTray<CableTray>(cableTrays[1]);
			if (!hycableTray.IsParallel(hycableTray2.CableTray))
			{
				throw new MyException("桥架必须平行");
			}
			IList<Connector> list = new List<Connector>();
			list = hycableTray.GetAppropriateConnector(cableTrays[1]);
			if (list[0] == null || list[1] == null || (list[0].IsConnected && list[1].IsConnected))
			{
				throw new MyException("桥架已经连接");
			}
			Transaction transaction = null;
			try
			{
				transaction = new Transaction(document, "Transition");
				transaction.Start();
				if (hycableTray.IsCableTrayOnLine(hycableTray2.CableTray) && hycableTray.CableTray.Width == hycableTray2.CableTray.Width && hycableTray.CableTray.Height == hycableTray2.CableTray.Height)
				{
					if (hycableTray.Combine(hycableTray2.CableTray))
					{
						result = true;
					}
				}
				else
				{
					XYZ endXYZ = hycableTray2.EndXYZ;
					XYZ lineProject = hycableTray.GetLineProject(endXYZ);
					double length = (endXYZ - new XYZ(lineProject.X, lineProject.Y, endXYZ.Z)).GetLength();
					double length2 = (endXYZ - new XYZ(endXYZ.X, endXYZ.Y, lineProject.Z)).GetLength();
					double num = (hycableTray.CableTray.Width + hycableTray2.CableTray.Width) / 2.0;
					double num2 = (hycableTray.CableTray.Height + hycableTray2.CableTray.Height) / 2.0;
					if (length <= num && length2 <= num2)
					{
						CableTrayFitingSel.GetCableTrayFittingType(document, CableTrayFittingType.Transition, hycableTray);
						if (document.Create.NewTransitionFitting(list[0], list[1]) != null)
						{
							result = true;
						}
					}
				}
				transaction.Commit();
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
                    if ((int)status != 3 && (int)status != 2)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
